package com.yanggeng.demo.beginnerguidedemo.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import com.yanggeng.demo.beginnerguidedemo.utils.DeviceUuidFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;

public class DeviceParams {

    private static final String TAG = "DeviceParams";
    public static final String NETWORK_TYPE_NONE = "none";
    public static final String NETWORK_TYPE_WIFI = "wifi";
    public static final String NETWORK_TYPE_MOBILE = "mobile";

    /**
     * 得到设备的deviceid
     *
     * @param context
     * @return
     */
    public static String deviceid(Context context) {
        // TelephonyManager telephonyManager = (TelephonyManager) context
        // .getSystemService(Context.TELEPHONY_SERVICE);
        // return telephonyManager.getDeviceId();
        return new DeviceUuidFactory(context).getDeviceUuid().toString();
    }

    /**
     * 获取MAC
     *
     * @return
     */
    public static String getMac() {
        String macSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);


            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return macSerial;
    }

    /**
     * 得到Android API Level
     *
     * @return
     */
    public static int buildSDK() {
        return Build.VERSION.SDK_INT;
    }

    /**
     * 获取Android发布版本号，如2.3.7
     *
     * @return
     */
    public static String osVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * @return current Android API level.
     */
    public static int apiLevel() {
        try {
            // Although the Build.VERSION.SDK field has existed since API 1, it
            // is deprecated and could be removed
            // in the future. Therefore use reflection to retrieve it for
            // maximum forward compatibility.
            final Class<?> buildClass = Build.VERSION.class;
            final String sdkString = (String) buildClass
                    .getField("SDK").get(null); //$NON-NLS-1$
            return Integer.parseInt(sdkString);
        } catch (final Exception e) {

            // Although probably not necessary, protects from the aforementioned
            // deprecation
            try {
                final Class<?> buildClass = Build.VERSION.class;
                return buildClass.getField("SDK_INT").getInt(null); //$NON-NLS-1$
            } catch (final Exception ignore) {
            }
        }

        // Worse-case scenario, assume Cupcake
        return 3;
    }

    /**
     * Gets the device manufacturer's name. This is only available on SDK 4 or
     * greater, so on SDK 3 this method returns the constant string "unknown".
     *
     * @return A string naming the manufacturer
     */
    public static String getManufacturer() {
        String mfg = "unknown"; //$NON-NLS-1$
        if (apiLevel() > 3) {
            try {
                final Class<?> buildClass = Build.class;
                mfg = (String) buildClass.getField("MANUFACTURER").get(null); //$NON-NLS-1$
            } catch (final Exception ignore) {
            }
        }
        return mfg;
    }

    public static String getModel() {
        String mfg = "unknown"; //$NON-NLS-1$
        if (apiLevel() > 3) {
            try {
                final Class<?> buildClass = Build.class;
                mfg = (String) buildClass.getField("MODEL").get(null); //$NON-NLS-1$
            } catch (final Exception ignore) {
            }
        }
        return mfg;
    }

    /**
     * 获取当前数据连接类型
     *
     * @param context
     * @return
     */
    public static String networkType(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netWorkInfo = connectivityManager.getActiveNetworkInfo();
        if (netWorkInfo == null || !netWorkInfo.isConnected()) {
            return NETWORK_TYPE_NONE;
        } else {
            switch (netWorkInfo.getType()) {
                case ConnectivityManager.TYPE_MOBILE:
                    return NETWORK_TYPE_MOBILE;
                case ConnectivityManager.TYPE_WIFI:
                    return NETWORK_TYPE_WIFI;
            }
            return NETWORK_TYPE_MOBILE;
        }
    }

    /**
     * 获取当前网络运营商名称
     *
     * @param context
     * @return
     */
    public static String networkOperator(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getNetworkOperatorName();
    }

    /**
     * 当前设备屏幕的宽(像素)
     *
     * @param context
     * @return
     */
    public static int screenWidth(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    /**
     * 当前设备屏幕的高(像素)
     *
     * @param context
     * @return
     */
    public static int screenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        // final int phoneScreenWidth = display.getWidth();
        return display.getHeight();
    }

    /**
     * 当前设备屏幕的密度
     *
     * @param context
     * @return
     */
    public static float density(Context context) {
        // return context.getResources().getDisplayMetrics().densityDpi;
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getMetrics(metrics);
        return metrics.density;
    }

    /**
     * Gets the versionName of the application.
     *
     * @param context {@link Context}. Cannot be null.
     * @return The application's version
     */
    public static String appVersion(final Context context) {
        final PackageManager pm = context.getPackageManager();

        try {
            final String versionName = pm.getPackageInfo(
                    context.getPackageName(), PackageManager.GET_ACTIVITIES).versionName;

            /*
             * If there is no versionName in the Android Manifest, the
             * versionName will be null.
             */
            if (versionName == null) {
                return "unknown"; //$NON-NLS-1$
            }

            return versionName;
        } catch (final PackageManager.NameNotFoundException e) {
            /*
             * This should never occur--our own package must exist for this code
             * to be running
             */
            throw new RuntimeException(e);
        }
    }

    /**
     * wang
     * Gets the versionCode of the application.
     *
     * @param context {@link Context}. Cannot be null.
     * @return The application's version
     */
    public static int appVersionCode(final Context context) {
        final PackageManager pm = context.getPackageManager();

        try {
            final int versionCode1 = pm.getPackageInfo(
                    context.getPackageName(), PackageManager.GET_ACTIVITIES).versionCode;

            /*
             * If there is no versionName in the Android Manifest, the
             * versionName will be null.
             */
//			if (versionCode) {
//				return "unknown"; //$NON-NLS-1$
//			}

            return versionCode1;
        } catch (final PackageManager.NameNotFoundException e) {
            /*
             * This should never occur--our own package must exist for this code
             * to be running
             */
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取name对应的AndroidManifest中的meta-data值
     *
     * @param context
     * @param name
     * @return
     */
    public static String metaData(Context context, String name) {
        try {
            PackageManager packageManager = context.getPackageManager();
            ApplicationInfo applicationInfo = packageManager
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (applicationInfo == null) {
                return "";
            } else {
                Bundle bundle = applicationInfo.metaData;
                String result = bundle.getString(name);
                if (result == null) {
                    return "";
                } else {
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 将sp值转换为px值
     *
     * @param context
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获取导航栏高度
     *
     * @param context
     * @return
     */
    public static int getNavigationHeight(Context context) {
        int result = 0;
        int resourceId = 0;
        int rid = context.getResources().getIdentifier("config_showNavigationBar", "bool", "android");
        if (rid != 0 && context.getResources().getBoolean(rid)) {
            resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
            Log.e("DeviceParam", "高度：" + context.getResources().getDimensionPixelSize(resourceId) + "");
            return context.getResources().getDimensionPixelSize(resourceId);
        } else
            return 0;
    }
}